#include "framelessWidget.h"
#include "ui_framelessWidget.h"
#include <QColor>
#include <QAction>
#include <QGraphicsDropShadowEffect>
#include <QDebug>
#include <QThread>


framelessWidget::framelessWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::framelessWidget)
{
    ui->setupUi(this);
    ui->mainWidget->setMouseTracking(true);  // 允许鼠标跟踪
    ui->mainDisplayWidget->setMouseTracking(true);
    setMouseTracking(true);

    QTimer *t = new QTimer(this);
    connect(t, &QTimer::timeout, this, [=](){Init();});
    t->setSingleShot(true);
    t->start(10);

    connect(ui->Button_close,&QPushButton::clicked, this,[=]()  // 点击关闭按钮
    {
        this->close();
    });

    ui->pushButton->setFixedSize(QSize(100,40));
    ui->pushButton_2->setFixedSize(QSize(100,40));


    ui->lineEdit_password->setPlaceholderText(QString("密码"));
    ui->lineEdit_username->setPlaceholderText(QString("用户名"));

    //给密码输入栏右侧添加图标(只有选中情况下才会显示眼睛图标)
    QAction *action = new QAction(this);
    action->setIcon(QIcon(":/pic/preview-close.png"));
    connect(ui->lineEdit_password,&QtMaterialAutoComplete::textEdited,this,[=]
    {
        static bool first = true;
        if(first)
        {
            ui->lineEdit_password->addAction(action,QLineEdit::TrailingPosition);
            first = false;
        }
    });
    int stat = 0;
    connect(action,&QAction::triggered,this,[=]()mutable{
        if(stat == 0)
        {
            action->setIcon(QIcon(":/pic/eyes-open.png"));
            ui->lineEdit_password->addAction(action,QLineEdit::TrailingPosition);
            stat = 1;
            ui->lineEdit_password->setEchoMode(QLineEdit::Normal);
        }
        else if(stat == 1)
        {
            action->setIcon(QIcon(":/pic/preview-close.png"));
            ui->lineEdit_password->addAction(action,QLineEdit::TrailingPosition);
            ui->lineEdit_password->setEchoMode(QLineEdit::Password);
            stat = 0;
        }
    });

    ui->lineEdit_username->setTextColor(QColor(192,192,192));
    ui->lineEdit_password->setTextColor(QColor(192,192,192));
    // 给按钮加阴影
    QGraphicsDropShadowEffect* effect1 = new QGraphicsDropShadowEffect(this);
    effect1->setBlurRadius(8);
    effect1->setColor(Qt::gray);
    effect1->setOffset(1,1);
    QGraphicsDropShadowEffect* effect2 = new QGraphicsDropShadowEffect(this);
    effect2->setBlurRadius(8);
    effect2->setColor(Qt::gray);
    effect2->setOffset(1,1);
    ui->pushButton->setGraphicsEffect(effect1);
    ui->pushButton_2->setGraphicsEffect(effect2);


    ui->Tips_Column->setFixedHeight(20);


    /******注册抽屉******/
     newWidget = new QWidget(this);
     newWidget->setStyleSheet("border-top-left-radius:20;border-bottom-left-radius:20");
     newWidget->setGeometry(30,30,this->width()-60,this->height()-48);
     QVBoxLayout *layout = new QVBoxLayout;
     newWidget->setLayout(layout);
     registDrawer = new QtMaterialDrawer(this);
     layout->addWidget(registDrawer);
     registDrawer->setClickOutsideToClose(true);
     registDrawer->setOverlayMode(true);
     this->setAttribute(Qt::WA_TransparentForMouseEvents, true);


     // 给抽屉设置遮罩以获得圆角轮廓
     registDrawer->setStyleSheet("background-color:rgb(251, 251, 251);border-top-left-radius:20;border-bottom-left-radius:20;border-right: 2px solid white");
    #ifdef Q_OS_LINUX
         QPainterPath path;
         path.addRect(newWidget->rect());
    #else
         QPainterPath path;
         path.addRoundedRect(newWidget->rect(), cornerRadius-1 , cornerRadius-1 );
    #endif
         QRegion mask(path.toFillPolygon().toPolygon());
         newWidget->setMask(mask);
    //添加子控件
     QVBoxLayout *drawerLayout = new QVBoxLayout;
     registDrawer->setDrawerLayout(drawerLayout);

     QVector<QString> labels = {"用户名", "密码", "联系电话"};
     QVector<QtMaterialTextField*> TextField;
     TextField.clear();
     QVector<QString>::iterator it;
     for (it = labels.begin(); it != labels.end(); ++it) {
         QtMaterialTextField *lineedit = new QtMaterialTextField(registDrawer);
         lineedit->setLabel(*it);
         lineedit->setMinimumHeight(30);
         lineedit->setFont(QFont("Roboto", 10, QFont::Medium));
         drawerLayout->addWidget(lineedit);
         TextField.push_back(lineedit);
     }

//     drawerLayout->addStretch(3);
     drawerLayout->setContentsMargins(30, 10, 30, 0);
     QPushButton *confirm = new QPushButton(registDrawer);
     registDrawer->setAttribute(Qt::WA_TransparentForMouseEvents, false);
     confirm->setText("确认");
     confirm->setStyleSheet("  QPushButton {\
                            border: 0.5px solid white;\
                            border-radius: 6px;\
                            background-color: rgb(90,194,198);\
                            min-width: 80px;\
                            font-family: \"Microsoft YaHei\";\
                            font-size:11pt;\
                            font-weight: bold;\
                            color:white;\
                        }\
                       QPushButton:hover {\
                          border: 0.5px solid white;\
                            border-radius: 6px;\
                            background-color: #1fab89;\
                            min-width: 80px;\
                            font-family: \"Microsoft YaHei\";\
                            font-size:10pt;\
                            font-weight: bold;\
                            color:white;\
                       }");
     drawerLayout->addWidget(confirm);
     connect(confirm,&QPushButton::clicked,this,[=]{
        QString username = TextField[0]->text();
        QString password = TextField[1]->text();
        QString phonenum = TextField[2]->text();
        if(!username.isEmpty()&&!password.isEmpty()&&!phonenum.isEmpty())
        {
            //执行注册流程
        }
     });


}

framelessWidget::~framelessWidget()
{
    delete ui;

}

void framelessWidget::Init()
{
    // 获取遮罩的轮廓并给mainWidget设置遮罩
    // 遮罩的作用是重叠的部分才可以看到

    #ifdef Q_OS_LINUX
        QPainterPath path;
        path.addRect(ui->mainWidget->rect());
    #else
        QPainterPath path;
        path.addRoundedRect(ui->mainWidget->rect(), cornerRadius-1 , cornerRadius-1 );
    #endif
        QRegion mask(path.toFillPolygon().toPolygon());
        ui->mainWidget->setMask(mask);
        // 给mainwidget添加样式
        QString mainStyle;
        ui->mainWidget->setObjectName("mainWidget");
        mainStyle = "QWidget#mainWidget{background-color:rgb(251, 251, 251)"  + QString::asprintf(";border-radius:%dpx", cornerRadius) + "}";
        ui->mainWidget->setStyleSheet(mainStyle);
    #if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
    #ifdef Q_OS_WINDOWS
        windowShadow = new QGraphicsDropShadowEffect(this);
        windowShadow->setBlurRadius(30);
        windowShadow->setColor(QColor(0, 0, 0));
        windowShadow->setOffset(0, 0);
        ui->mainWidget->setGraphicsEffect(windowShadow);
    #endif
    #endif
        /**********************************************************/

        /* 添加border的 widget以遮盖锯齿边缘 */
    #ifdef Q_OS_WINDOWS
        border = new QWidget(this);
        border->move(ui->mainWidget->pos() - QPoint(1, 1));
        border->resize(ui->mainWidget->size() + QSize(2, 2));
        QString borderStyle;
        borderStyle = "background-color:#00FFFFFF;border:1.5px solid #686868; border-radius:" + QString::asprintf("%d",cornerRadius) + "px";
        border->setStyleSheet(borderStyle);
        border->setAttribute(Qt::WA_TransparentForMouseEvents);
        border->show();
    #endif
        /*****************************************************************/
}

// 鼠标按下事件(记录拉伸窗口或移动窗口时的起始坐标（左上角）)
void framelessWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        mousePressed = true;

#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
        lastPos = event->globalPosition().toPoint() - this->frameGeometry().topLeft();
#else
        lastPos = event->globalPos() - this->frameGeometry().topLeft();
#endif
    }

    if (this->parentWidget())
        {
            qDebug()<<"有反应"<<endl;
            //点下去的那一刻屏蔽当前窗口及其所有子部件的事件，此时被当前窗口遮挡住的父窗口的控件的事件被响应
            //为什么不到这里就结束，因为如果这样做，只要点击过一次，当前窗口及其子部件就再也不会响应鼠标事件，比如移入移出
            //因此点击之后还必须要把这个屏蔽取消掉
            //但如果中间什么也不做的话，这个属性的设置就没有意义，因为最终是false
            //所以需要手动将鼠标点击事件下发给父窗口中的对应部件
            this->setAttribute(Qt::WA_TransparentForMouseEvents, true);
            QPoint point = this->mapTo(this->parentWidget(), event->pos());    //将点击事件在当前部件的坐标转换为在父窗口坐标系中的坐标
            QWidget *widget = this->parentWidget()->childAt(point);   //判断当前点击的位置是否是父窗口的一个子部件
            if (widget)
            {
                point = widget->mapFrom(this->parentWidget(), point);    //将当前部件在父窗口的坐标转为在当前部件自己的坐标系中的坐标
                QMouseEvent *mouseEvent = new QMouseEvent(event->type(), point, event->button(), event->buttons(), event->modifiers());
                QApplication::postEvent(widget, mouseEvent);
            }
            this->setAttribute(Qt::WA_TransparentForMouseEvents, false);
        }

}

// 鼠标移动事件
void framelessWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::NoButton)
        mousePressed = false;
    if(!mousePressed){ // 鼠标没按下移动，更新鼠标位置状态
        mouseState = 0;
        if(!maximized && abs(event->pos().x() - ui->mainWidget->pos().x()) < 5)
            mouseState |= AT_LEFT;
        if(!maximized && abs(event->pos().y() - ui->mainWidget->pos().y()) < 5)
            mouseState |= AT_TOP;
        if(!maximized && abs(event->pos().x() - ui->mainWidget->pos().x() - ui->mainWidget->width()) < 5)
            mouseState |= AT_RIGHT;
        if(!maximized && abs(event->pos().y() - ui->mainWidget->pos().y() - ui->mainWidget->height()) < 5)
            mouseState |= AT_BOTTOM;
        if(mouseState == AT_TOP_LEFT  || mouseState == AT_BOTTOM_RIGHT)
            setCursor(Qt::SizeFDiagCursor);
        else if(mouseState == AT_TOP_RIGHT || mouseState == AT_BOTTOM_LEFT)
            setCursor(Qt::SizeBDiagCursor);
        else if(mouseState & (AT_LEFT | AT_RIGHT))
            setCursor(Qt::SizeHorCursor);
        else if(mouseState & (AT_TOP | AT_BOTTOM))
            setCursor(Qt::SizeVerCursor);
        else
            unsetCursor();
    }
    else{ //鼠标按下移动
        if(mouseState == 0){
            if(maximized){
                qreal wRatio = (double)event->pos().x() / (double)ui->mainWidget->width();
                controlWindowScale();
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
                this->move(QPoint(event->globalPosition().x() - ui->mainWidget->width() * wRatio, -30));
#else
                this->move(QPoint(event->globalPos().x() - ui->mainWidget->width() * wRatio, -30));
#endif
                lastPos = QPoint(ui->mainWidget->width() * wRatio, event->pos().y());
            }
            else
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
                this->move(event->globalPosition().toPoint() - lastPos);
#else
                this->move(event->globalPos() - lastPos);
#endif
        }
        else{
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
            QPoint d = event->globalPosition().toPoint() - frameGeometry().topLeft() - lastPos;
#else
            QPoint d = event->globalPos() - frameGeometry().topLeft() - lastPos;
#endif
            if(mouseState & AT_LEFT){
                this->move(this->frameGeometry().x() + d.x(), this->frameGeometry().y());
                this->resize(this->width() - d.x(), this->height());
            }
            if(mouseState & AT_RIGHT){
                this->resize(this->width() + d.x(), this->height());
            }
            if(mouseState & AT_TOP){
                this->move(this->frameGeometry().x(), this->frameGeometry().y() + d.y());
                this->resize(this->width(), this->height() - d.y());
            }
            if(mouseState & AT_BOTTOM){
                this->resize(this->width(), this->height() + d.y());
            }
        }
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
        lastPos = event->globalPosition().toPoint() - this->frameGeometry().topLeft();
#else
        lastPos = event->globalPos() - this->frameGeometry().topLeft();
#endif
    }
}

// 窗口变化事件
void framelessWidget::resizeEvent(QResizeEvent *event)
{
    //Resize border
    if(border)
        border->resize(ui->mainWidget->size() + QSize(2, 2));

    //Resize mask
    QPainterPath path;
#ifdef Q_OS_WINDOWS
    path.addRoundedRect(ui->mainWidget->rect(), cornerRadius - 1, cornerRadius - 1);
#else
    path.addRect(ui->mainWidget->rect());
#endif
    QRegion mask(path.toFillPolygon().toPolygon());
    ui->mainWidget->setMask(mask);

//    newWidget->setGeometry(30,30,this->width()-60,this->height()-60);
//#ifdef Q_OS_LINUX
//     QPainterPath path;
//     path.addRect(newWidget->rect());
//#else
//     QPainterPath path_dreaer;
//     path.addRoundedRect(newWidget->rect(), cornerRadius-1 , cornerRadius-1 );
//#endif
//     QRegion mask_drawer(path.toFillPolygon().toPolygon());
//     newWidget->setMask(mask);
}

//点击最大化按钮事件
void framelessWidget::controlWindowScale(){
#ifdef Q_OS_WINDOWS
    if(!maximized){
        lastGeometry = this->frameGeometry();
      //  windowShadow->setEnabled(false);
        ui->verticalLayout->setContentsMargins(0, 0, 0, 0);
        border->hide();
        QString mainStyle = "QWidget#mainWidget{background-color:rgb(251,251,251) border-radius:0px;}";
        ui->mainWidget->setStyleSheet(mainStyle);
        this->showMaximized();
        maximized = true;
        QPainterPath path;
        path.addRect(ui->mainWidget->rect());
        QRegion mask(path.toFillPolygon().toPolygon());
        ui->mainWidget->setMask(mask);
    }
    else{
        ui->verticalLayout->setContentsMargins(30, 30, 30, 30);
        this->showNormal();
        QString mainStyle = "QWidget#mainWidget{background-color:rgb(251,251,251)" + QString::asprintf(";border-radius:%dpx", cornerRadius) + "}";
        ui->mainWidget->setStyleSheet(mainStyle);
        QPainterPath path;
        path.addRoundedRect(ui->mainWidget->rect(), cornerRadius - 1, cornerRadius - 1);
        QRegion mask(path.toFillPolygon().toPolygon());
        ui->mainWidget->setMask(mask);
        border->show();
     //   windowShadow->setEnabled(true);
        this->resize(lastGeometry.width(), lastGeometry.height());
        this->move(lastGeometry.x(), lastGeometry.y());
        maximized = false;
    }
#endif
}


void framelessWidget::on_pushButton_clicked()
{
    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    if(password.isEmpty()&&username.isEmpty())
    {
        ui->Tips_Column->textlable->setText("请输入用户名和密码");
        ui->Tips_Column->animationStart();
    }
    else if(password.isEmpty())
    {
        ui->Tips_Column->textlable->setText("请输入密码");
        ui->Tips_Column->animationStart();
    }
    else if(username.isEmpty())
    {
        ui->Tips_Column->textlable->setText("请输入用户名");
        ui->Tips_Column->animationStart();
    }
    else
    {
       //执行登录流程
    }

}




void framelessWidget::on_pushButton_2_clicked()
{
        registDrawer->openDrawer();
}
